package io.terminus.spzx.manager.service.impl;

import io.terminus.spzx.common.log.annotation.SpzxLog;
import io.terminus.spzx.manager.mapper.SysRoleMenuMapper;
import io.terminus.spzx.manager.service.SysMenuService;
import io.terminus.spzx.manager.service.SysRoleMenuService;
import io.terminus.spzx.model.dto.system.AssignMenuDto;
import io.terminus.spzx.model.entity.system.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 系统角色与菜单绑定Service实现类
 * @Date 2024-09-03
 */
@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public Map<String, Object> findSysRoleMenuByRoleId(Long roleId) {
        Map<String, Object> map = new HashMap<>(2);
        // 1、查询所有菜单
        List<SysMenu> menuList = sysMenuService.findNodes();
        map.put("sysMenuList", menuList);

        // 2、根据角色ID查询绑定的菜单ID列表
        List<Long> roleMenuIdList = sysRoleMenuMapper.findSysRoleMenuByRoleId(roleId);
        map.put("roleMenuIds", roleMenuIdList);

        return map;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @SpzxLog(title = "保存角色分配的菜单", businessType = 2)
    public void doAssign(AssignMenuDto assignMenuDto) {
        // 1、删除角色分配菜单数据
        sysRoleMenuMapper.deleteByRoleId(assignMenuDto.getRoleId());

        // 2、保存分配数据
        if (!CollectionUtils.isEmpty(assignMenuDto.getMenuIdList())) {
            sysRoleMenuMapper.doAssign(assignMenuDto);
        }
    }
}
